//
//  ATKit+UITableViewCell.swift
//  ATKit_Swift
//
//  Created by wangws1990 on 2020/12/3.
//  Copyright © 2020 wangws1990. All rights reserved.
//

import UIKit

public extension UITableViewCell{
    static var confiTag : Int = 32241983
    class func cellForTableView(tableView:UITableView,indexPath:IndexPath) ->Self{
       return self.cellForTableView(tableView: tableView, indexPath: indexPath, identifier: nil, config: nil)
    }
    class func cellForTableView(tableView:UITableView,indexPath:IndexPath,identifier:String? = nil,config:((_ cell :UITableViewCell) ->())? = nil) ->Self{
        let identy  = identifier ?? NSStringFromClass(self.classForCoder())
        var cell = tableView.dequeueReusableCell(withIdentifier: identy)
        if cell == nil {
            if let _ = Bundle.main.url(forResource:self.xibName(), withExtension:"nib"){
                tableView.register(UINib(nibName:self.xibName(), bundle:nil), forCellReuseIdentifier: identy)
            }else{
                tableView.register(self.classForCoder(), forCellReuseIdentifier: identy)
            }
            cell = tableView.dequeueReusableCell(withIdentifier:identy)
        }
        if cell?.tag != confiTag {
            cell?.tag = confiTag
            if let config = config,let cell = cell {
                config(cell)
            }
        }
        return cell as! Self
    }
}

public extension UITableView{
    func cellForTableView<T :UITableViewCell>(tableCell :T.Type,indexPath:IndexPath) ->T{
        let tableView  = self
        let identy  = NSStringFromClass(tableCell.classForCoder())
        var cell = tableView.dequeueReusableCell(withIdentifier: identy)
        guard let newCell = cell else {
            if let _ = Bundle.main.url(forResource:tableCell.xibName(), withExtension:"nib"){
                tableView.register(UINib(nibName:tableCell.xibName(), bundle:nil), forCellReuseIdentifier: identy)
            }else{
                tableView.register(tableCell.classForCoder(), forCellReuseIdentifier: identy)
            }
            cell = tableView.dequeueReusableCell(withIdentifier:identy)
            return cell as! T
        }
        return newCell as! T
     }
}
